package com.lkd.handler;

import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-08-23 14:21
 */
@Component
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
@Slf4j
public class OrderCheckHandler implements MsgHandler {


    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPayTemplate wxPayTemplate;

    @Override
    public void process(String jsonMsg) throws IOException {
        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);
        if(StringUtils.isBlank(orderCheck.getOrderNo())){
            log.error("订单延迟消息中订单号为空" + jsonMsg);
            return;
        }

        OrderEntity order = orderService.getByOrderNo(orderCheck.getOrderNo());
        if(order == null){
            log.error("订单未找到!" + jsonMsg);
            return;
        }

        //1.判断订单是否处于未支付状态，修改状态为取消
        if(Objects.equals(order.getPayStatus(), VMSystem.PAY_STATUS_NOPAY)){
            order.setStatus(VMSystem.ORDER_STATUS_INVALID);
            orderService.updateById(order);
        }

        //2.调用微信接口，将二维码失效
        WxPayParam wxPayParam = new WxPayParam();
        wxPayParam.setOutTradeNo(order.getOrderNo());
        try {
            wxPayTemplate.closeOrder(wxPayParam);
        } catch (Exception e) {
            log.error("关闭微信订单失败"+jsonMsg,e);
        }
    }
}
